<?php

/**
 * 概要描述：
 * @author: lin
 * @since: 2020-03-11 9:46
 */

namespace app\common\controller;


use app\BaseController;
use app\common\model\ManageRoleOperationRel;
use app\common\model\Operation;
use app\common\model\OperationLog;
use think\exception\HttpResponseException;
use think\facade\Log;
use think\facade\View;

class AdminController extends BaseController {
  protected function initialize() {
    parent::initialize();

    //没有登陆，请先登录
    if (!session('?manage')) {
      cookie('redirect_url', request()->url(true), 3600);
      return $this->redirect(url('login/login'));
    }

    $cont_name = request()->controller();
    $act_name  = request()->action();

    $operationModel = new Operation();

    //判断当前是否有权限操作
    $mrorModel = new ManageRoleOperationRel();
    $permRe    = $mrorModel->checkPerm(session('manage.id'), $operationModel::MENU_MANAGE, $cont_name, $act_name);

    if ($permRe['status'] != 0) {
      if (request()->isAjax()) {
        $err = [
          'status' =>  $permRe['status'],
          'datas'   => [],
          'msg'    => $permRe['msg']
        ];
        echo json_encode($err);
        die();
      } else {
        $this->error($permRe['msg']);
      }
    }

    $shop_name = getSetting('shop_name');
    View::assign('shop_name', $shop_name);
    View::assign('menu', []);
    View::layout('layout');
    $this->record();
  }

  public function record() {
    $user       = session('manage');
    if (request()->isPost()) {
      $ctl          = strtolower(request()->controller());
      $act          = strtolower(request()->action());
      $operation = new Operation();
      $opinfo    = $operation->getOperationInfo($ctl, $act, $operation::MENU_MANAGE);

      if ($opinfo['status']) {
        $postData = input('post.');
        $decs     = $opinfo['data']['act']['name'];
        $log      = [
          'manage_id'  => $user['id'],
          'controller' => $ctl,
          'method'     => $act,
          'desc'       => $decs,
          'content'    => json_encode($postData),
          'ip'         => get_client_ip(0, true),
        ];
        $logModel = new OperationLog();
        $logModel->doAdd($log);
      } else {
        Log::record(json_encode($opinfo));
      }
    }
  }


  public function redirect(...$args) {
    throw new HttpResponseException(redirect(...$args));
  }
}
